<script setup lang="ts">
import { ref, shallowReactive, computed, watch } from 'vue'
import { onLoad, onShow, onUnload } from '@dcloudio/uni-app'
import orderGoodSpec from '@/components/order/order-good-spec.vue'
import shopNav from '@/components/order/shop-nav.vue'
import DefaultEmpty from '@/components/qszr-core/packages/components/q-empty/default-empty.vue'
import OrderUnpaySpec from './components/order-unpay-spec.vue'
import { computeOrderPrice } from '@/hooks/price/order'
import { queryStatus, isCloseOrder, isPayOrder } from '@/hooks/useOrderStatus'
import { useStoreInfoStore } from '@/store/modules/storeInfo'
import { useOrderStoreMap } from '@/store/modules/order'
import { doGetOrder } from '@/apis/order'
import type { ApiOrder, ShopOrderItem, ShopOrder } from './types'
import { doPostOrderStockUp } from '@/apis/order'
import type { DoPostOrderStockUpQuery } from '@/apis/order/model'
import type { DoGetStoreInfoByShopAssistantPhoneResponse } from '@/apis/home/model'
import Auth from '@/components/auth/auth.vue'

type PLATFORM = 'WECHAT_MINI_APP' | 'WECHAT_MP' | 'PC' | 'H5' | 'IOS' | 'ANDROID' | 'HARMONY'
interface ExtraMap {
  AllDeliveryCount: string
  miniDeliveryCount: string
}

const { divTenThousand } = useConvert()
const orderList = ref<ApiOrder[]>([])
const $useStoreInfoStore = useStoreInfoStore() as { shopStoreInfo: DoGetStoreInfoByShopAssistantPhoneResponse }
const $useOrderStoreMap = useOrderStoreMap()
const tabList = ref<{ name: string; label: string }[]>([])
const uTabSwiper = ref()
const currentTabIndex = ref(0)
const isEmpty = ref(false)
const shopId = computed(() => $useStoreInfoStore.shopStoreInfo.shopId)
const shopStoreId = computed(() => $useStoreInfoStore.shopStoreInfo.id)
const pageConfig = shallowReactive({
  size: 10,
  current: 1,
})
const customStyle = {
  width: '150rpx',
  height: '60rpx',
  padding: '20rpx',
  margin: '0',
  marginLeft: '15rpx',
  color: '#4755E9',
}
const extraMap = ref<ExtraMap>({ AllDeliveryCount: '0', miniDeliveryCount: '0' })
const platformIconMap: Record<PLATFORM, string> = {
  WECHAT_MINI_APP: 'icon-xiaochengxu',
  WECHAT_MP: 'icon-weixin',
  H5: 'icon-shouji2',
  IOS: 'icon-iOS',
  PC: 'icon-zhuomian-diannaoxianshiqi',
  ANDROID: 'icon-anzhuo',
  HARMONY: 'icon-huawei',
}

initTab()
onLoad(({ id }) => {
  currentTabIndex.value = Number(id) || 0
  initList(currentTabIndex.value)
})
onUnload(() => {
  pageConfig.current = 1
})
uni.$on('pathIndex', ({ msg }) => {
  currentTabIndex.value = msg
  initList(currentTabIndex.value)
})

function initTab() {
  const temp = []
  temp.push({ name: '全部', label: '' })
  for (const [key, value] of Object.entries(queryStatus)) {
    temp.push({ name: value, label: key })
  }
  tabList.value = temp
}
async function initList(index: number, loadMore = false) {
  const shopOrderMap: Map<string, boolean> = new Map()
  isEmpty.value = false
  const { size, current } = pageConfig

  const { code, data } = await doGetOrder({
    size,
    current,
    status: tabList.value[index].label,
    shopStoreId: $useStoreInfoStore.shopStoreInfo.id,
    isMiniAppTip: true,
  }).catch(() => {
    isEmpty.value = true
  })

  if (code !== 200) {
    isEmpty.value = true
    uni.showToast({ icon: 'none', title: '获取订单列表失败' })
    return
  }
  extraMap.value = data.extraMap
  const orders: ApiOrder[] = []
  data.records.forEach((order: ApiOrder) => {
    const newShopOrders: ShopOrder[] = []
    const closedShoOrders: ShopOrder[] = []
    const shopOrders = order.shopOrders
    for (let i = 0; i < shopOrders.length; i++) {
      const shopOrder = shopOrders[i]
      if (shopOrder.status === 'SELLER_CLOSED') {
        closedShoOrders.push(shopOrder)
        continue
      }
      shopOrderMap.set(shopOrder.orderNo, false)
      shopOrder.isCheck = false
      const packMap = initOrder(shopOrder)
      const packItems = packMap.get('')
      if (packItems?.length) {
        shopOrder.shopOrderItems = packItems
        newShopOrders.push(shopOrder)
      }
      packMap.delete('')
      for (let [key, value] of packMap.entries()) {
        const cloneShopOrder = { ...shopOrder }
        cloneShopOrder.shopOrderItems = value
        newShopOrders.push(cloneShopOrder)
      }
    }
    if (newShopOrders.length > 0) {
      order.shopOrders = newShopOrders
      orders.push(order)
    }
    if (closedShoOrders.length > 0) {
      const newOrder = { ...order }
      newOrder.status = 'SELLER_CLOSED'
      newOrder.shopOrders = closedShoOrders
      orders.push(newOrder)
    }
  })
  if (loadMore) {
    orderList.value = orderList.value.concat(orders)
  } else {
    orderList.value = orders
  }
  isEmpty.value = true
  $useOrderStoreMap.SET_ORDER_MAP(shopOrderMap)
}
/**
 * 订单按发货 | 未发货区分
 */
function initOrder(shopOrder: ShopOrder) {
  const map = new Map<string, ShopOrderItem[]>()
  const items = shopOrder.shopOrderItems
  map.set('', [])
  for (let i = 0; i < items.length; i++) {
    const item = items[i]
    if (item.packageStatus === 'WAITING_FOR_DELIVER') {
      map.get('')?.push(item)
      continue
    }
    const packageId = item.packageId
    const packageItems = map.get(packageId as string)
    if (packageItems) {
      packageItems.push(item)
      continue
    }
    map.set(packageId as string, [item])
  }
  return map
}
/**
 * 导航去订单详情(未支付的订单没有拆分店铺传orderNo即可)
 */
const handleNavToDetail = (orderNo: string, shopId?: string, packageId?: string) => {
  const baseUrl = `/pages/orderDetail/OrderDetail?orderNo=${orderNo}&packageId=${packageId ? packageId : ''}`
  if (!shopId) {
    uni.navigateTo({ url: baseUrl })
    return
  }
  const url = `${baseUrl}&shopId=${shopId}`
  uni.navigateTo({ url })
}
/**
 * tabs切换 列表重置 获取新数据
 */
const handletabsChange = (index: number) => {
  pageConfig.current = 1
  currentTabIndex.value = index
  orderList.value = []
  $useOrderStoreMap.isAll = false
  initList(index)
}
/**
 * 触底请求下一页
 */
const handleScrolltolower = () => {
  if (pageConfig.size * pageConfig.current > orderList.value.length) {
    return
  }
  pageConfig.current++
  initList(currentTabIndex.value, true)
}
const handleCheckAllChange = (e: { value: boolean; name: string }) => {
  $useOrderStoreMap.SET_ORDER_MAP_All(e.value)
}
/**
 * 准货完成
 */
const handleReadyComplete = (orderNos: string[]) => {
  uni.showModal({
    title: '请确认',
    content: `请确认是否${orderNos.length > 1 ? '批量备货' : '备货'}(发货)完成`,
    success: function (res) {
      if (res.confirm) {
        const param = {
          orderNos,
          shopId: shopId.value,
          shopStoreId: shopStoreId.value,
        }
        console.log('param', param)
        orderStockUp(param)
      } else if (res.cancel) {
        console.log('用户点击取消')
      }
    },
  })
}
async function orderStockUp(param: DoPostOrderStockUpQuery) {
  const { code, data, msg } = await doPostOrderStockUp(param)
  if (code !== 200) return uni.$msg(msg ? msg : '备货失败')
  uni.$msg('备货成功')
  //重新load
  initList(currentTabIndex.value)
}
const useOrderStoreMapCheckKa = computed(() => {
  const arr = []
  for (const iterator of $useOrderStoreMap.orderMap) {
    if (iterator[1]) {
      arr.push(iterator[0])
    }
  }
  return arr
})
</script>
<template>
  <u-tabs
    ref="uTabSwiper"
    v-model="currentTabIndex"
    :list="tabList"
    bg-color="#fff"
    active-color="#4755E9"
    :show-bar="false"
    height="90"
    swiper-width="750"
    @change="handletabsChange"
  />
  <view v-if="currentTabIndex === 1 && Number(extraMap?.AllDeliveryCount || 0) >= 1" class="reminder">
    <u-icon name="info-circle-fill" size="46rpx" color="#F60404" />
    <view class="reminder__right">
      您共有 <span>{{ extraMap.AllDeliveryCount }}</span> 笔待发货的订单，其中小程序端订单有
      <span>{{ extraMap.miniDeliveryCount || 0 }}</span> 笔，超过 48 小时未发货，将触发支付风险提示，直至暂停小程序交易!!!
    </view>
  </view>
  <view v-if="currentTabIndex === 1" class="bulkstock">
    <u-checkbox v-model="$useOrderStoreMap.isAll" @change="handleCheckAllChange">全选</u-checkbox>
    <u-button
      shape="circle"
      size="medium"
      :custom-style="customStyle"
      style="width: 220rpx"
      :disabled="!useOrderStoreMapCheckKa.length"
      @click.stop="handleReadyComplete(useOrderStoreMapCheckKa)"
    >
      批量备货完成
    </u-button>
  </view>
  <scroll-view v-show="orderList.length" :scroll-y="true" class="order" @scrolltolower="handleScrolltolower">
    <view v-for="order in orderList" :key="order.no" :class="{ order__item: order.status !== 'PAID' }">
      <!-- 已支付订单多列展示 -->
      <template v-if="order.status === 'PAID'">
        <view v-for="(shop, index) in order.shopOrders" :key="index" class="order__item">
          <shop-nav :info="shop" :show-checkbox="currentTabIndex === 1" />
          <view
            v-for="item in shop.shopOrderItems"
            :key="item.id"
            @click.stop="handleNavToDetail(order.no, shop.shopId, shop.shopOrderItems[0].packageId)"
          >
            <order-good-spec :key="item.skuId" :info="item" :order-list-show-afs-status="true" :navigate-to-goods-info="false" />
          </view>
          <view v-if="isCloseOrder(order.status)" class="order__realPay">
            实付款
            <text class="order__realPay--number">{{ divTenThousand(computeOrderPrice(shop).toString()) }} </text>
          </view>

          <view v-if="currentTabIndex === 1" class="order__footer-btn">
            <q-icon color="#101010" :name="platformIconMap[order.platform as PLATFORM]" size="46rpx"></q-icon>
            <u-button shape="circle" size="medium" :custom-style="customStyle" @click.stop="handleReadyComplete([shop.orderNo])"> 备货完成 </u-button>
          </view>
        </view>
      </template>
      <!-- 未支付单列展示 -->
      <!---->
      <order-unpay-spec v-else :order="order" />
    </view>
  </scroll-view>
  <default-empty
    v-if="isEmpty && !orderList.length"
    title="暂无订单"
    height="700rpx"
    background="https://obs.xiaoqa.cn/gruul/20220630/ebca8a56db6e4187ab8cd54bf6955d37.png"
  />
  <Auth />
</template>

<style lang="scss" scoped>
@import '@/assets/css/mixins/mixins.scss';
@include b(order) {
  box-sizing: border-box;
  padding: 10rpx 12rpx;
  height: calc(100vh - 178rpx);
  @include e(footer-btn) {
    margin-top: 16rpx;
    // text-align: right;
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
  @include e(item) {
    box-sizing: border-box;
    border-radius: 10rpx;
    background: #fff;
    margin-bottom: 14rpx;
    padding: 0 20rpx 20rpx 20rpx;
  }
  @include e(item-header) {
    @include flex(space-between);
    height: 90rpx;
    @include m(left) {
      @include flex();
    }
    @include m(right) {
      color: #f12f22;
    }
  }
  @include e(realPay) {
    font-size: 28rpx;
    font-weight: bold;
    text-align: right;
    @include m(number) {
      font-size: 34rpx;
      &::before {
        content: '￥';
        display: inline-block;
      }
    }
  }
}
.bulkstock {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20rpx;
  height: 90rpx;
  margin-bottom: 14rpx;
}
@include b(reminder) {
  display: flex;
  // align-items: center;
  height: 100rpx;
  width: 100%;
  background-color: #fdc3c3;
  font-size: 24rpx;
  padding: 18rpx 12rpx 6rpx 6rpx;
  @include e(right) {
    span {
      color: #f72020;
      font-weight: bold;
    }
  }
}
</style>
